package com.welfare.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.UnsupportedEncodingException;
import java.security.spec.AlgorithmParameterSpec;

public class DESUtils {
    public static final String DES_ALGORITHM = "DES/CBC/PKCS5Padding";
    // 若采用NoPadding模式，data长度必须是8的倍数
//	public static final String DES_ALGORITHM = "DES/CBC/NoPadding";

    private static final String Key= DigestUtils.MD5("key!(*&").substring(0,8).toUpperCase();

    private static Logger logger = LoggerFactory.getLogger(DESUtils.class);

    /**
     * DES-CBC模式加密
     *
     * @param plainData
     *            明文
     * @param keyData
     *            密钥
     * @param ivData
     *            初始化向量
     * @return 密文
     */
    public static final byte[] encryptCBC(byte[] plainData, byte[] keyData, byte[] ivData) {
        byte[] encryptData = null;

        try {
            Cipher cipher = Cipher.getInstance(DES_ALGORITHM);
            DESKeySpec desKeySpec = new DESKeySpec(keyData);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // 密钥
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivData);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
            encryptData = cipher.doFinal(plainData);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return encryptData;
    }

    /**
     * DES-CBC模式解密
     *
     * @param encryptData
     *            密文
     * @param keyData
     *            密钥
     * @param ivData
     *            初始化向量
     * @return 明文
     */
    public static final byte[] decryptCBC(byte[] encryptData, byte[] keyData, byte[] ivData) {
        byte[] plainData = null;

        try {
            Cipher cipher = Cipher.getInstance(DES_ALGORITHM);
            DESKeySpec desKeySpec = new DESKeySpec(keyData);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // 密钥
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivData);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
            plainData = cipher.doFinal(encryptData);
        } catch (Exception e) {
            logger.error("ex:{}",e);
        }
        return plainData;
    }

    public static String encrypt(String string){
        byte[] bytes= new byte[0];
        try {
            bytes = encryptCBC(string.getBytes("GBK"),Key.getBytes("GBK"),Key.getBytes("GBK"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0,j=bytes.length; i < j; i++) {
//            String hexString = Integer.toHexString(0xff & bytes[i]);
            String hexString=String.format("%x",bytes[i]);
            if (hexString.length() < 2) {
                hexString = "0" + hexString;
            }
            stringBuffer.append(hexString);
        }
        return stringBuffer.toString().toUpperCase();
    }
    public static String decrypt(String string) throws Exception {
        if(StringUtils.isEmpty(string)){
            return null;
        }
        int len;
        len = string.length() / 2;
        byte[] inputByteArray = new byte[len];
        int x, i;
        for (x = 0; x < len; x++)
        {
            i = Integer.parseInt(string.substring(x * 2, x * 2+2), 16);
            inputByteArray[x] = (byte)i;
        }
        try {
            return new String(decryptCBC(inputByteArray,Key.getBytes("GBK"),Key.getBytes("GBK")),"GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("DES解码异常！");
        }
    }

    public static void main(String[] args) {
        String str= encrypt("13841589279");
        System.out.println(str);
    }

}
